import { ref, computed } from 'vue';
import type { UserRole } from '../components/Login.vue';

type ViewType = 'room' | 'admin' | 'frontdesk' | 'manager';

// 角色权限映射
const rolePermissions: Record<UserRole, ViewType[]> = {
  guest: ['room'],
  admin: ['admin'],
  frontdesk: ['frontdesk'],
  manager: ['manager'],
  superadmin: ['room', 'admin', 'frontdesk', 'manager']
};

// 角色名称映射
const roleNames: Record<UserRole, string> = {
  guest: '房客',
  admin: '管理员',
  frontdesk: '前台',
  manager: '经理',
  superadmin: '超级管理员'
};

export function useAuth() {
  const currentUser = ref<UserRole | null>(null);
  const userName = ref<string>('');
  const currentView = ref<ViewType>('room');

  // 登录处理
  const handleLogin = (role: UserRole) => {
    currentUser.value = role;
    userName.value = roleNames[role];
    
    // 根据角色自动切换到对应的默认视图
    const permissions = rolePermissions[role];
    if (permissions.length > 0 && permissions[0]) {
      currentView.value = permissions[0];
    }
  };

  // 登出处理
  const handleLogout = () => {
    currentUser.value = null;
    userName.value = '';
    currentView.value = 'room';
  };

  // 检查权限
  const hasPermission = (view: ViewType): boolean => {
    if (!currentUser.value) return false;
    return rolePermissions[currentUser.value].includes(view);
  };

  // 可访问的视图
  const availableViews = computed(() => {
    if (!currentUser.value) return [];
    return rolePermissions[currentUser.value];
  });

  // 切换视图
  const switchView = (view: ViewType) => {
    currentView.value = view;
  };

  return {
    currentUser,
    userName,
    currentView,
    availableViews,
    handleLogin,
    handleLogout,
    hasPermission,
    switchView
  };
}

